import time
import multiprocessing
from wish.app.ys_pool_case import get_case

title = 'case statistics calculator'
process_count = 32
times_per_process = 40000
wish_times = 730


def process_func(result_list, process_num, process_lock):
    rl_case_map = {}
    process_name = multiprocessing.current_process().name
    tpp = times_per_process
    percent = tpp / 100
    for index in range(tpp):
        case = get_case(wish_times)
        if rl_case_map.__contains__(case):
            rl_case_map[case] += 1
        else:
            rl_case_map[case] = 1
        if index % percent == 0:
            print(f'{process_name} - {index / percent}/100')
    process_lock.acquire()
    result_list.append(rl_case_map)
    process_lock.release()
    print('process', process_num, 'complete.')


if __name__ == '__main__':
    t = time.time()
    process_list = []
    lock = multiprocessing.Lock()
    rll = multiprocessing.Manager().list()
    r_case_map = {}

    for i in range(process_count):
        process_list.append(multiprocessing.Process(
            target=process_func, args=(rll, i, lock)))
    for process in process_list:
        process.start()
    for process in process_list:
        process.join()

    for case_map in rll:
        for k in case_map.keys():
            if r_case_map.__contains__(k):
                r_case_map[k] += case_map[k]
            else:
                r_case_map[k] = case_map[k]

    print()
    print(title)
    # print(r_case_map)
    k_list = sorted(r_case_map.keys())
    for k in k_list:
        print(k[1], ':', '{:.2%}'.format(r_case_map[k] / (process_count * times_per_process)))
        # print('{:.2%}'.format(r_case_map[k] / (process_count * times_per_process)))
    print('run in:', time.time() - t, 's')
